/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package filesecurity;

import java.io.File;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author lehoangkhanh
 */
public class SignForm extends javax.swing.JInternalFrame {

    /**
     * Creates new form SignForm
     */
    String fileName = null;
    String filePath = null;
    String folderPath = null;
    MainFrame rootFrame = null;
    public SignForm(MainFrame root) {
        initComponents();
        rootFrame = root; 
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        passphrase = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        savein = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setTitle("Sign Form");

        jLabel1.setText("PassPhrase:");

        jLabel2.setText("Save in:");

        savein.setText("...");
        savein.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveinActionPerformed(evt);
            }
        });

        jButton2.setText("OK<<");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(passphrase)
                    .addComponent(savein, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(9, 9, 9)
                        .addComponent(jButton2)))
                .addContainerGap(33, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(passphrase, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(savein))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void saveinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveinActionPerformed
        // TODO add your handling code here:
        JFileChooser file = new JFileChooser();
        file.setSelectedFile(new File(rootFrame.getFileName()+".sig"));
        int op = file.showSaveDialog(null);
        if(op == JFileChooser.APPROVE_OPTION){
            filePath = file.getCurrentDirectory().getPath().toString();
            fileName = file.getSelectedFile().getName();
            savein.setText("Just Selected...");
            savein.setToolTipText(filePath);
        }
    }//GEN-LAST:event_saveinActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
       if(passphrase.getText().equals("")){
            JOptionPane.showMessageDialog(rootPane, "PassPhrase is NULL!!!");
            return;
        }
        if(fileName==null || fileName.equals("")){
            JOptionPane.showMessageDialog(rootPane, "Please select location of output file!!!");
            return;
        }
        User currentUser = rootFrame.getCurrentUser();
        boolean validState = Crypto.checkHash(passphrase.getText().getBytes(), currentUser.getHashPassPhrase(), currentUser.getSaltPassPhrase());
        if(validState == false){
            JOptionPane.showMessageDialog(rootPane, "PassPhrase is not valid!!!");
            return;
        }
        byte[] file = Utils.readFile(rootFrame.getFilePath());
        byte[] encryptedPriKey = currentUser.getEncryptedPrivateKey();
        byte[] priKeyByte =  Crypto.decryptFile(encryptedPriKey, KeyFac.sKeyGenWithPass(passphrase.getText()), Crypto.AES, "itisnotcareabout".getBytes());
        if(priKeyByte == null){
            JOptionPane.showMessageDialog(rootPane, "Error!!!Please try again");
            return;
        }
        PrivateKey priKey = null;
        try {
            priKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(priKeyByte));
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(DecryptForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeySpecException ex) {
            Logger.getLogger(DecryptForm.class.getName()).log(Level.SEVERE, null, ex);
        }
        byte[] sign = DigitalSign.sign(file, priKey);
        if(sign == null){
            JOptionPane.showMessageDialog(rootPane, "Error!!!Please try again");
            return;
        }
        Utils.writeFile(sign, filePath+"/"+fileName);
        JOptionPane.showMessageDialog(rootPane, "Successfull!!!");
        this.setVisible(true);
    }//GEN-LAST:event_jButton2ActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField passphrase;
    private javax.swing.JButton savein;
    // End of variables declaration//GEN-END:variables
}
